package main

import (
	"fmt"
	"go-exp/exp-test/orm-test/config"
	"go-exp/pkg/yaml"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
	"os"
	"path/filepath"
	"sync"
	"time"
)

type Model struct {
	// 主键 id
	ID uint `gorm:"primarykey"`
	// 创建时间
	CreatedAt time.Time
	// 更新时间
	UpdatedAt time.Time
	// 删除时间
	DeletedAt gorm.DeletedAt `gorm:"index"`
}

var (
	// 全局 db 模式
	db *gorm.DB
	// 单例工具
	dbOnce sync.Once
)

func getDB(dsn string) (*gorm.DB, error) {
	var err error
	dbOnce.Do(func() {
		// 创建 db 实例
		db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	})
	return db, err
}

func main() {
	fmt.Println("Hello World")
	cwd, err := os.Getwd()
	if err != nil {
		log.Fatalf("获取当前目录失败: %v", err)
	}
	path := filepath.Join(cwd, "orm-test/dns.yaml")
	dns := config.DnsConfig{}
	yaml.ParsingYaml(&dns, path)
	dsnStr := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", dns.User, dns.Pass, dns.Host, dns.Port, dns.Db)
	_, err = getDB(dsnStr)
	if err != nil {
		return
	}
	err = db.Migrator().AutoMigrate(&Model{})
	if err != nil {
		return
	}
	fmt.Println(dns)
	model := Model{}
	db.Where("id = ?", 1).First(&model)
	fmt.Println(model)

	models := []Model{}
	for i := range 1000 {
		models = append(models, Model{uint(i), time.Now(), time.Now(), gorm.DeletedAt{}})
	}
	db.Create(&models)
	db.Delete(&models)
}
